package com.alifi.crm.web.home.action;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.alibaba.buc.sso.client.util.SimpleUserUtil;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.common.lang.StringUtil;
import com.alibaba.common.logging.Logger;
import com.alibaba.common.logging.LoggerFactory;
import com.alibaba.platform.buc.sso.common.dto.SimpleSSOUser;
import com.alifi.crm.biz.guess.Base;
import com.alifi.crm.biz.guess.GuessMessage;
import com.alifi.crm.biz.score.EmployeeScoreManager;
import com.alifi.crm.dal.enu.States;
import com.alifi.crm.dal.object.EmployeeScoreDO;


/**
 * 
 * @author wenjing.huangwj
 *
 */
public class ScoreAction {

	@Resource(name="employeeScoreManager")
	EmployeeScoreManager employeeScoreManager;
	
	protected static final Logger      logger = LoggerFactory.getLogger(ScoreAction.class);
	protected static final Logger      logPermission = LoggerFactory.getLogger("uums-permission-logger");
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @param ctx
	 */
	public void doScore(HttpServletRequest request, HttpServletResponse response,Navigator nav,final Context ctx){
	
		try {
			ctx.put("action", "true");   //标记进入过action
			SimpleSSOUser user = SimpleUserUtil.findUser(request);
			if((user==null)||StringUtil.isBlank(user.getEmpId())){      //检查
				ctx.put("message", GuessMessage.NOT_GET_LOGIN_INFO);
				return;
			}
			if (logPermission.isInfoEnabled()) {
				logPermission.info(user.getEmpId()+ "  start score  by  ScoreAction");
			}
			
			ctx.put("user", user);
			EmployeeScoreDO scoreDO = employeeScoreManager.getEmployeeScore(Base.toSixBitSmployee(user.getEmpId()));
		    if(scoreDO==null){
		    	ctx.put("message", GuessMessage.NOT_FOUND_EMPLOYEE);
		    	return;
		    }
		    ctx.put("guessDO", scoreDO);
		    
		    if(States.结束.equals(scoreDO.getScoreStates())){
		    	ctx.put("message", GuessMessage.SCORE_END);
		    	return;
		    }else{
		    	ctx.put("continue_score", true);
		    }
		    
		    String signScore = StringUtil.trim(request.getParameter("sign_score"));
		    String payScore  =  StringUtil.trim(request.getParameter("pay_score"));
		    String amountScore   = StringUtil.trim(request.getParameter("amount_score"));
		    String wholeScore = StringUtil.trim(request.getParameter("whole_score"));
		    boolean checkResult = checkScoreStr(signScore,payScore,amountScore,wholeScore);
		    if(!checkResult){
		    	ctx.put("message", GuessMessage.SCORE_NOT_ALLOW);
		    	return;
		    }
		    employeeScoreManager.score(scoreDO.getEmployeeNum(),Long.parseLong(signScore),Long.parseLong(payScore),Long.parseLong(amountScore),Long.parseLong(wholeScore)); 
		    ctx.put("message", GuessMessage.SCORE_SUCCESS);
		    
		} catch (Exception e) {
			ctx.put("message", new GuessMessage("exception",e.getMessage(),""));
			logger.error(e);
		} finally{
			printlnJsonDate(response,ctx);
		}
	}
	
	
	private boolean checkScoreStr(String signScoreStr, String payScoreStr, String amountScoreStr, String wholeScoreStr){
		if(StringUtil.isBlank(signScoreStr)||StringUtil.isBlank(payScoreStr)||StringUtil.isBlank(amountScoreStr)||StringUtil.isBlank(wholeScoreStr)){
			return false;
		}
		try{
			Long signScore = Long.parseLong(StringUtil.trim(signScoreStr));
			Long payScore = Long.parseLong(StringUtil.trim(payScoreStr));
			Long uiScore = Long.parseLong(StringUtil.trim(amountScoreStr));
			Long wholeScore = Long.parseLong(StringUtil.trim(wholeScoreStr));
			return checkScore(signScore,payScore,uiScore,wholeScore);
		}
		catch(Exception e){
			logger.error(e);
			return false;
		}
	}
	
	
	/**
	 * 如果任何一个入参数>5或<1，返回false. 否则返回true
	 * @param signScore
	 * @param payScore
	 * @param uiScore
	 * @param wholeScore
	 * @return
	 */
	private boolean checkScore(Long signScore, Long payScore, Long uiScore, Long wholeScore){
		if(!check(signScore)){
			return false;
		}
		if(!check(payScore)){
			return false;
		}
		if(!check(uiScore)){
			return false;
		}
		if(!check(wholeScore)){
			return false;
		}
		return true;
	}
	
	/**
	 * 如果score>5或<1 返回false.  否则返回ture
	 * @param score
	 * @return
	 */
	private boolean check(Long score){
		if((score==null)||(score>5)||(score<1)){
			return false;
		}
		return true;
	}
	
	
	
	/**
	 * json中一定包含  message,code,pic
	 * @param response
	 * @param ctx
	 * @throws IOException
	 */
	private void printlnJsonDate(HttpServletResponse response,final Context ctx){
		JSONObject object = new JSONObject();
		if(ctx.get("message")!=null){
			GuessMessage guessMessage = (GuessMessage)ctx.get("message");
			object.put("message", guessMessage.getMessage());
			object.put("code", guessMessage.getCode());
			if(ctx.get("continue_score")!=null){
				object.put("continue_score", "true");
			}
		}
		try {
			response.getWriter().println(object.toString());
		} catch (IOException e) {
			logger.error(e);
		}
	}
	
	
	

	


}
